//
//  XS_ZhengshuVC.swift
//  XueDao
//
//  Created by 韩云智 on 2020/12/6.
//

import UIKit

class XS_queryMyIndustryAllM: XS_BaseModel {
    var count = 0 // 参考人数
    var imgUrl = "" // 证书图片地址
    var name = "" // 证书名称
    var id = 0 // 证书id
}
class XS_queryOtherIndustryAllM: XS_BaseModel {
    var certificateBOs: [XS_queryMyIndustryAllM] = [] // 证书集合
    var industryName = "" // 行业名称
    var id = 0 // 行业id
}

class XS_ZhengshuVC: XS_BaseVC {
    lazy var tags: [XS_HomeTopM] = []
    lazy var zView = UIView()
    var allModels: [XS_queryMyIndustryAllM]!
    
    lazy var mineZhengShuData: [XS_HomeTopM] = []
    lazy var otherZhengShuData: [XS_HomeTopM] = []
    
    lazy var pageView = getPageView()
    lazy var segment = getSegment()
    
    lazy var topContentBgScv: UIScrollView = {
        let topContentBgScv = UIScrollView()
        topContentBgScv.bounces = false
        topContentBgScv.contentInsetAdjustmentBehavior = .never
        topContentBgScv.showsHorizontalScrollIndicator = false
        return topContentBgScv
    }()
    
    lazy var topNaviBgScv: UIScrollView = {
        let topNaviBgScv = UIScrollView()
        topNaviBgScv.showsHorizontalScrollIndicator = false
        return topNaviBgScv
    }()
    
    lazy var lineView: UIView = {
        let lineView = UIView()
        lineView.backgroundColor = UIColor(red: 0.16, green: 0.74, blue: 0.61, alpha: 1.00)
        lineView.layer.masksToBounds = true
        lineView.layer.cornerRadius = .scale * 1
        return lineView
    }()

    override func upView() {
        title = "证书百科"
        
        let item = UIBarButtonItem(image: UIImage(named: "icon_搜索"), style: .done, target: nil, action: nil)
        navigationItem.rightBarButtonItem = item
        item.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                guard let `self` = self, let aModels = self.allModels else { return }
                let vc = XS_ZhengshuSearchVC()
                vc.models = aModels
                self.navigationController?.pushViewController(vc, animated: true)
            }).disposed(by: disposeBag)
        
        let scroll = UIScrollView()
        scroll.bounces = false
        scroll.contentInsetAdjustmentBehavior = .never
        view.addSubview(scroll)
        scroll.snp.makeConstraints({$0.edges.equalToSuperview()})
        
        let view1 = UIView(frame: CGRect(x: 0, y: 0, width: .screenWidth, height: .scale*88))
        scroll.addSubview(view1)
        do {
            let label = UILabel.xsLabel(size: .scale*18, fontName: .semibold, color: #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1), text: "我的行业证书")
            view1.addSubview(label)
            label.snp.makeConstraints({
                $0.top.equalToSuperview()
                $0.left.equalTo(.scale*16)
                $0.height.equalTo(.scale * 56)
            })
            
            view1.addSubview(topNaviBgScv)
            topNaviBgScv.snp.makeConstraints { (make) in
                make.top.equalTo(.scale * 56)
                make.left.right.equalToSuperview()
                make.height.equalTo(.scale * 32)
            }
            topNaviBgScv.addSubview(lineView)
            lineView.snp.makeConstraints { (make) in
                make.top.equalTo(.scale * 29)
                make.height.equalTo(.scale * 3)
                make.width.equalTo(.scale * 20)
                make.centerX.equalTo(-.scale * 20)
            }
        }

        topContentBgScv.frame = CGRect(x: 0, y: .scale*104, width: .screenWidth, height: .scale*160)
        scroll.addSubview(topContentBgScv)
        
        let line = UIView(frame: CGRect(x: 0, y: .scale*276, width: .screenWidth, height: .scale*8))
        line.backgroundColor = #colorLiteral(red: 0.968627451, green: 0.968627451, blue: 0.968627451, alpha: 1)
        scroll.addSubview(line)
        let view2 = UIView(frame: CGRect(x: 0, y: .scale*284, width: .screenWidth, height: .scale*56))
        scroll.addSubview(view2)
        do {
            let label = UILabel.xsLabel(size: .scale*18, fontName: .semibold, color: #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1), text: "其他行业证书")
            view2.addSubview(label)
            label.snp.makeConstraints({
                $0.centerY.equalToSuperview()
                $0.left.equalTo(.scale*16)
            })
//            let button = XS_NoHighlightBtn()
//            button.setImage(UIImage(named: "icon_12px_删选"), for: .normal)
//            button.setTitle(" 筛选行业", for: .normal)
//            button.setTitleColor(#colorLiteral(red: 0.4470588235, green: 0.4666666667, blue: 0.4862745098, alpha: 1), for: .normal)
//            button.titleLabel?.font = .xsFont(name: .regular, .scale*14)
//            view2.addSubview(button)
//            button.snp.makeConstraints({
//                $0.centerY.equalToSuperview()
//                $0.right.equalTo(-.scale*16)
//            })
//            button.rx.tap.asDriver()
//                .drive(onNext: { [weak self] in
//                    guard XS_Singleton.shared.infoModel != nil else {
//                        XS_NVC.shared.toLogin(false)
//                        return
//                    }
//                    let vc = XS_HangyeVC()
//                    vc.texts = ["我感兴趣的行业证书", "可删除不感兴趣的行业", "点击添加感兴趣的行业证书，可多选"]
//                    vc.tags = self?.tags ?? []
//                    self?.present(vc, animated: true)
//                }).disposed(by: disposeBag)
        }
        scroll.addSubview(zView)
        zView.snp.makeConstraints({
            $0.width.left.bottom.equalToSuperview()
            $0.top.equalTo(view2.snp.bottom)
            $0.height.equalTo(view.bounds.size.height - .scale*300 - .barHeight - 49)
        })
        
//        XS_Singleton.shared.changeZhengshu = { [weak self] tags in
//            self?.tags = tags
//            self?.reload(s)
//        }
        
        loadTopViewData()
    }
    
    func loadTopViewData() {
        XS_NetWork.requestJson("/industry/queryAllStatusApi")
            .mapModels(type: XS_HomeTopM.self)
            .subscribe(onNext: { [weak self] models, resp in
                guard let `self` = self, resp.success else { return }
                for (_, subData) in models.enumerated() {
                    if subData.selected == "yes" {
                        self.mineZhengShuData.append(subData)
                    }
                }
                self.reloadSubIndustry(data: self.mineZhengShuData)
            }).disposed(by: disposeBag)
        
        XS_NetWork.requestJson("/industry/queryAllIndustryBySearchType", parameters: ["searchType" : "certificate"])
            .mapModels(type: XS_HomeTopM.self)
            .subscribe(onNext: { [weak self] models, resp in
                guard let `self` = self, resp.success else { return }
                for (_, subData) in models.enumerated() {
                    if subData.selected == "no" {
                        self.otherZhengShuData.append(subData)
                    }
                }
                
                self.allModels = []
                for model in models {
                    XS_NetWork.requestJson("/certificate/queryCertificateByIndustry", parameters: ["industryId" : model.id])
                        .mapModels(type: XS_queryOtherIndustryAllM.self)
                        .subscribe(onNext: { [weak self] subModels, resp in
                            guard let `self` = self, resp.success else { return }
                            self.allModels += subModels.flatMap({ $0.certificateBOs })
                        }).disposed(by: self.disposeBag)
                }
                self.loadBottomViewData(data: self.otherZhengShuData)
            }).disposed(by: disposeBag)
    }
    
    func reloadSubIndustry(data: [XS_HomeTopM]) {
        for view in topNaviBgScv.subviews {
            if view.isKind(of: UIButton.self) {
                view.snp.removeConstraints()
                view.removeFromSuperview()
            }
        }
        var lastBtn: UIButton?
        for (index, item) in data.enumerated() {
            let btn = UIButton.init(type: .custom)
            btn.backgroundColor = .white
            btn.setTitle(item.industryName, for: .normal)
            btn.setTitleColor(UIColor(red: 0.60, green: 0.60, blue: 0.60, alpha: 1.00), for: .normal)
            btn.setTitleColor(UIColor(red: 0.22, green: 0.24, blue: 0.25, alpha: 1.00), for: .selected)
            btn.titleLabel?.font = btn.isSelected ? .systemFont(ofSize: .scale * 14, weight: .semibold) : .systemFont(ofSize: .scale * 14, weight: .regular)
            btn.tag = index
            btn.addTarget(self, action: #selector(didScrollView(btn:)), for: .touchUpInside)
            topNaviBgScv.addSubview(btn)
            btn.snp.makeConstraints { (make) in
                make.top.equalToSuperview()
                make.height.equalTo(.scale * 29)
                if let last = lastBtn {
                    make.left.equalTo(last.snp.right).offset(.scale * 24)
                } else {
                    make.left.equalTo(.scale * 16)
                    btn.isSelected = true
                }
                if index == data.count - 1 {
                    make.right.lessThanOrEqualTo(-.scale * 16)
                }
            }
            lastBtn = btn
        }
        didScrollView(to: 0)
    }
    
    @objc func didScrollView(btn: UIButton) {
        didScrollView(to: btn.tag)
    }
    
    func didScrollView(to btnIndex: Int) {
        reloadTopViewData(topContentBgScv, index: btnIndex)
        for items in topNaviBgScv.subviews {
            if let item = items as? UIButton {
                if item.tag == btnIndex {
                    item.isSelected = true
                    UIView.animate(withDuration: 0.2) {
                        self.lineView.center.x = item.center.x
                        self.lineView.bounds.size.width = item.bounds.size.width
                        self.lineView.snp.remakeConstraints { (make) in
                            make.top.equalTo(.scale * 29)
                            make.height.equalTo(.scale * 3)
                            make.width.equalTo(item)
                            make.centerX.equalTo(item)
                        }
                    }
                } else {
                    item.isSelected = false
                }
            }
        }
    }
    
    func reloadTopViewData(_ s: UIScrollView, index: Int) {
        if self.mineZhengShuData.count > 0 {
            XD_BlankPageView.hiddenBlankPageView(superView: s)
            let mineZhengshuM = self.mineZhengShuData[index]
            XS_NetWork.requestJson("/certificate/queryCertificateByIndustry", parameters: ["industryId":mineZhengshuM.id])
                .mapModels(type: XS_queryOtherIndustryAllM.self)
                .subscribe(onNext: { [weak self] models, resp in
                    guard let `self` = self, resp.success else { return }
                    s.removeSubviews()
                    if models.count > 0 {
                        XD_BlankPageView.hiddenBlankPageView(superView: s)
                        for model in models {
                            for (index, item) in model.certificateBOs.enumerated() {
                                let view = self.getMineZhengshu(item)
                                s.addSubview(view)
                                view.snp.makeConstraints({
                                    $0.width.equalTo(.scale*88)
                                    $0.top.height.equalToSuperview()
                                    $0.left.equalTo(.scale*16 + .scale*CGFloat(index*(88+16)))
                                    $0.right.lessThanOrEqualToSuperview().offset(-.scale*16)
                                })
                            }
                        }
                    } else {
                        self.showEmptDataView(superV: s)
                    }
                }).disposed(by: disposeBag)
        } else {
            self.showEmptDataView(superV: s)
        }
    }
    
    private func showEmptDataView(superV: UIView) {
        let blankPageView = XD_BlankPageView()
        superV.addSubview(blankPageView)
        blankPageView.blankPage(imgName: "缺省页_暂无内容", detailStr: "暂无此行业证书，请添加其他行业", bottomDetailStr: "")
        blankPageView.snp.makeConstraints { (make) in
            make.centerX.top.bottom.equalToSuperview()
            make.left.right.lessThanOrEqualToSuperview()
        }
        blankPageView.imgView.snp.remakeConstraints { (make) in
            make.top.equalTo(10)
            make.centerX.equalToSuperview()
            make.width.height.equalTo(120)
        }
    }
    
    func loadBottomViewData(data: [XS_HomeTopM]) {
        if data.count > 0 {
            XD_BlankPageView.hiddenBlankPageView(superView: self.zView)
            self.reloadZView(data)
        } else {
            let blankPageView = XD_BlankPageView()
            blankPageView.blankPage(imgName: "缺省页_暂无内容", detailStr: "暂无证书~", bottomDetailStr: "")
            blankPageView.frame = CGRect.init(x: 0, y: 0, width: self.zView.frame.size.width, height: self.zView.frame.size.height)
            self.zView.addSubview(blankPageView)
        }
    }
    
    func reloadZView(_ items: [XS_HomeTopM]) {
        zView.removeSubviews()

        zView.addSubview(segment)
        zView.addSubview(pageView)
        segment.updateChannels(items.map({ $0.industryName }))
        pageView.removeAll()
        pageView.reloadData()
        if items.count > 0 {
            pageView.changeToItem(at: 0)
        }
        didScroll(to: 0)
    }
    
    func getMineZhengshu(_ item: XS_queryMyIndustryAllM) -> UIView {
        let view = UIView()
        let imgV = UIImageView()
        imgV.layer.cornerRadius = .scale*4
        imgV.clipsToBounds = true
        view.addSubview(imgV)
        imgV.snp.makeConstraints({
            $0.left.top.right.equalToSuperview()
            $0.height.equalTo(imgV.snp.width).multipliedBy(112.0/88.0)
        })
        
        let label1 = UILabel.xsLabel(size: .scale*14, fontName: .medium, color: #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1), lines: 1, text: item.name)
        view.addSubview(label1)
        label1.snp.makeConstraints({
            $0.top.equalTo(imgV.snp.bottom).offset(.scale*8)
            $0.left.right.equalToSuperview()
            $0.height.equalTo(.scale*20)
        })
        let label2 = UILabel.xsLabel(size: .scale*12, fontName: .regular, color: #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1), text: "\(item.count) 人参考")
        view.addSubview(label2)
        label2.snp.makeConstraints({
            $0.top.equalTo(label1.snp.bottom).offset(.scale*4)
            $0.left.right.bottom.equalToSuperview()
            $0.height.equalTo(.scale*16)
        })
        imgV.sd_setImage(with: URL(string: item.imgUrl))
        
        let tap = UITapGestureRecognizer()
        view.addGestureRecognizer(tap)
        tap.rx.event.asDriver()
            .drive(onNext: { [weak self] tap in
                self?.toDetail(item.id)
            }).disposed(by: disposeBag)
        return view
    }

    func getOtherZhengshu(_ item: XS_queryMyIndustryAllM) -> UIView {
        let view = UIView()
        let imgV = UIImageView()
        imgV.layer.cornerRadius = .scale*4
        imgV.clipsToBounds = true
        view.addSubview(imgV)
        imgV.snp.makeConstraints({
            $0.left.top.right.equalToSuperview()
            $0.height.equalTo(imgV.snp.width).multipliedBy(132.0/104.0)
        })
        
        let label1 = UILabel.xsLabel(size: .scale*14, fontName: .medium, color: #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1), lines: 1, text: item.name)
        view.addSubview(label1)
        label1.snp.makeConstraints({
            $0.top.equalTo(imgV.snp.bottom).offset(.scale*8)
            $0.left.right.equalToSuperview()
            $0.height.equalTo(.scale*20)
        })
        let label2 = UILabel.xsLabel(size: .scale*12, fontName: .regular, color: #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1), text: "\(item.count) 人参考")
        view.addSubview(label2)
        label2.snp.makeConstraints({
            $0.top.equalTo(label1.snp.bottom).offset(.scale*4)
            $0.left.right.bottom.equalToSuperview()
            $0.height.equalTo(.scale*16)
        })
        imgV.sd_setImage(with: URL(string: item.imgUrl))
        
        let tap = UITapGestureRecognizer()
        view.addGestureRecognizer(tap)
        tap.rx.event.asDriver()
            .drive(onNext: { [weak self] tap in
                self?.toDetail(item.id)
            }).disposed(by: disposeBag)
        return view
    }
    
    func toDetail(_ id: Int) {
        let vc = XS_ZhengshuDetailVC()
        vc.id = id
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

extension XS_ZhengshuVC: JXSegmentDelegate,JXPageViewDataSource,JXPageViewDelegate {
    
    func getSegment() -> JXSegment {
        let segment = JXSegment(frame: CGRect(x: 0, y: 0, width: .screenWidth, height: .scale*35))
        segment.delegate = self
        segment.scrollView.contentInsetAdjustmentBehavior = .never
        return segment
    }
    
    func getPageView() -> JXPageView {
        let pageView = JXPageView(frame: CGRect(x: 0, y: .scale*35, width: .screenWidth, height: view.bounds.size.height - .scale*316 - .scale*35))
        pageView.scrollview.contentInsetAdjustmentBehavior = .never
        pageView.datasource = self
        pageView.delegate = self
        return pageView
    }
    
    
    func jxSegment(_ segment: JXSegment!, didSelect index: Int) {
        pageView.changeToItem(at: index)
    }
    
    func numberOfItem(in pageView: JXPageView!) -> Int {
        self.otherZhengShuData.count
    }
    
    func pageView(_ pageView: JXPageView!, viewAt index: Int) -> UIView! {
        let scroll = UIScrollView()
        scroll.frame = pageView.bounds
        scroll.bounces = true
        scroll.contentInsetAdjustmentBehavior = .never
        
        let mj_header = MJRefreshNormalHeader()
        mj_header.tag = 1024
        scroll.mj_header = mj_header
        mj_header.rx.refresh
            .startWith(.refreshing)
            .subscribe(onNext: { [weak self] state in
                guard let `self` = self, state == .refreshing else { return }
                self.reload(scroll, index: index, mj_header: mj_header)
            }).disposed(by: disposeBag)
        
        return scroll
    }
    func reload(_ scroll: UIScrollView, index: Int, mj_header: MJRefreshNormalHeader) {
        let otherZhengShuModel = self.otherZhengShuData[index]
        XS_NetWork.requestJson("/certificate/queryCertificateByIndustry", parameters: ["industryId":otherZhengShuModel.id])
            .mapModels(type: XS_queryOtherIndustryAllM.self)
            .subscribe(onNext: { [weak self] models, resp in
                guard let `self` = self, resp.success else { return }
                scroll.removeSubviews()
                var top: CGFloat = -.scale*196
                for model in models {
                    for (index, item) in model.certificateBOs.enumerated() {
                        if index%3 == 0 {
                            top += .scale*196 + .scale*16
                        }
                        let view = self.getOtherZhengshu(item)
                        scroll.addSubview(view)
                        view.snp.makeConstraints({
                            $0.width.equalTo(.scale*104)
                            $0.height.equalTo(.scale*180)
                            $0.top.equalTo(top)
                            $0.left.equalTo(.scale*CGFloat(16 + index%3*(16+104)))
                            $0.bottom.lessThanOrEqualToSuperview().offset(-.scale*16)
                        })
                    }
                }
            }, onDisposed: {
                mj_header.endRefreshing()
            }).disposed(by: disposeBag)
    }
    
    func didScroll(to index: Int) {
        segment.didChenge(to: index)
    }
}
